package cn.xy.base.server.service.impl;

import cn.hutool.json.JSONUtil;
import cn.xy.base.server.dao.SysConfigDao;
import cn.xy.base.server.po.SysConfig;
import cn.xy.base.server.service.SysConfigService;
import cn.xy.commons.cache.CacheManager;
import cn.xy.commons.exception.JzRuntimeException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rustic.server.bean.WeixinConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * SysConfig对应的服务类实现
 *
 * @author auto
 */

@Slf4j
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigDao, SysConfig> implements SysConfigService {

    private static final String CONFIG_KEY = "config";
    private static final Map<String, Class<?>> KEY_MAP = new HashMap<>();

    @Autowired
    private CacheManager cacheManager;

    @Override
    public Class<?> getClass(String key) {
        return KEY_MAP.get(key);
    }

    static {
        KEY_MAP.put(STR, String.class);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getConfig(String key, Class<T> clazz) {
        T configValue = null;
        try {
            configValue = cacheManager.hget(CONFIG_KEY, key);
        } catch (Exception e) {
            log.info("getConfig error: {}", e.getMessage());
        }
        try {
            if (configValue != null) {
                return configValue;
            }
            configValue = clazz.getDeclaredConstructor().newInstance();
            LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysConfig::getKey, key);
            SysConfig config = this.getOne(queryWrapper);
            if (config != null) {
                if (clazz.isAssignableFrom(String.class)) {
                    configValue = (T) config.getValue();
                } else {
                    configValue = JSONUtil.toBean(config.getValue(), clazz);
                }
                cacheManager.hset(CONFIG_KEY, key, configValue);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return configValue;
    }

    @Override
    public <T> void saveConfig(String key, T value) {
        SysConfig config = new SysConfig();
        config.setKey(key);
        config.setValue(JSONUtil.toJsonStr(value));
        this.saveOrUpdate(config);
        cacheManager.hset(CONFIG_KEY, key, value);
    }

    @Override
    public WeixinConfig getWeixinConfig(String key) {
        WeixinConfig weixinConfig = this.getConfig(key, WeixinConfig.class);
        if (weixinConfig == null) {
            throw new JzRuntimeException("微信配置信息尚未初始化！");
        }
        return weixinConfig;
    }

}
